package com.acmedcare.framework.exchange.center.core;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;

public class CommonCommandListener {

  public static SimpleMessageListenerContainer addFanoutListener(
      MessageListenerAdapter messageListenerAdapter, String exchangeName,
      String queueName, RabbitTemplate rabbitTemplate) {

    RabbitAdmin admin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
    FanoutExchange exchange = new FanoutExchange(exchangeName);
    admin.declareExchange(exchange);

    Queue queue = new Queue(queueName, false, false,
        true);
    admin.declareQueue(queue);
    Binding binding = BindingBuilder.bind(queue).to(exchange);
    admin.declareBinding(binding);

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(rabbitTemplate.getConnectionFactory());
    container.setQueueNames(queue.getName());

    container.setMessageListener(messageListenerAdapter);
    container.start();
    return container;
  }
}
